<?php
/**
 * Created by PhpStorm.
 * User: Suley
 * For: Test
 * Date: 2018/12/05
 * Time: 12:53
 */

namespace app\api\controller;

use think\Exception;
use think\db\Expression;
use think\log;
use think\db;
use app\common\controller\Api;
use app\api\model\Standard as SD;
//use app\common\controller\Aes;
//use app\common\controller\Rsa;
use app\common\controller\Selfmcrypt;


class Mytest extends Api
{
    public function _initialize()
    {
        Log::init([
            'type' => 'File',
            'path' => APP_PATH . 'logs/'
        ]);
    }


    public function index(){

    }

    //同步产品&商品字段
    public function updateProductGoodsGoods(){
        $where_p['p.item_num'] = [["NEQ","null"],["NEQ",""],'and'];
        $where_p['g.goods_tcode'] = [["NEQ","null"],["NEQ",""],'and'];
        //产品字段
        //price费用包含，priceno费用不含，back退改规则，careful注意事项
        //商品字段
        //price_include费用包含，price_noinclude费用不含，goods_retreating退改规则，goods_careful注意事项
        $data = db("product")
            ->alias("p")
            ->join("goods g","p.item_num=g.goods_tcode","left")
            ->where($where_p)
            ->field("p.item_num,p.price,p.priceno,p.back,p.careful,p.sale_details,p.tag_id,g.price_include,g.price_noinclude,g.goods_retreating,g.goods_careful,g.goods_introduce,g.tag_id as gtag_id")
            ->select();

//        echo "<pre>";
//        var_dump($data);
//        echo "</pre>";
//        exit;

        if(!empty($data)){
            foreach ($data as $key=>$value) {
                $arr = [];
                $price_include_p = !empty($value['price']) ? $value['price'] : '';
                $price_include_g = !empty($value['price_include']) ? $value['price_include'] : '';

                $price_noinclude_p = !empty($value['priceno']) ? $value['priceno'] : '';
                $price_noinclude_g = !empty($value['price_noinclude']) ? $value['price_noinclude'] : '';

                $back_p = !empty($value['back']) ? $value['back'] : '';
                $back_g = !empty($value['goods_retreating']) ? $value['goods_retreating'] : '';

                $careful_p = !empty($value['careful']) ? $value['careful'] : '';
                $careful_g = !empty($value['goods_careful']) ? $value['goods_careful'] : '';

                $sale_details = !empty($value['goods_introduce']) ? $value['goods_introduce'] : '';

                $arr['item_num']= $value['item_num'];
                $arr['price_include'] = $price_include_p!=='' ? $price_include_p : $price_include_g;
                $arr['price_noinclude'] = $price_noinclude_p!=='' ? $price_noinclude_p : $price_noinclude_g;
                $arr['back'] = $back_p!=='' ? $back_p : $back_g;
                $arr['careful'] = $careful_p!=='' ? $careful_p : $careful_g;
                $arr['sale_details'] = $sale_details;
                $arr['tag_id']= $value['gtag_id'];

                $updateProductData = [];
//                $updateProductData['price'] = $arr['price_include'];
//                $updateProductData['priceno'] = $arr['price_noinclude'];
//                $updateProductData['back'] = $arr['back'];
//                $updateProductData['careful'] = $arr['careful'];
//                $updateProductData['sale_details'] = $arr['sale_details'];
//                $updateProductData['update_time'] = time();

                $updateProductData['tag_id'] = $arr['tag_id'];
                $resProduct = db("product")->where("item_num",$value['item_num'])->update($updateProductData);
                if($resProduct){
                    echo "【".$value['item_num']."产品已更新】<br>";
                }

//                $updateGoodsData = [];
//                $updateGoodsData['price_include'] = $arr['price_include'];
//                $updateGoodsData['price_noinclude'] = $arr['price_noinclude'];
//                $updateGoodsData['goods_retreating'] = $arr['back'];
//                $updateGoodsData['goods_careful'] = $arr['careful'];
//                $updateGoodsData['updatetime'] = time();
//                $resGoods = db("goods")->where("goods_tcode",$value['item_num'])->update($updateGoodsData);
//                if($resGoods){
//                    echo "【".$value['item_num']."商品已更新】<br><br>";
//                }
            }
        }

        exit;
    }


    public function showData(){
        //商品总数
        $totalCount = db("goods")->count();
        //在售中商品总数
        $onsaleTotalCount = db("goods")->where("goods_status",1)->count();

        //viator商品总数
        $viatorCount = db("goods")->where("show",2)->count();
        //在售中viator商品总数
        $onsaleViatorCount = db("goods")->where("show",2)->where("goods_status",1)->count();

        //自营商品总数
        $ownCount = db("goods")->where("show",1)->count();
        //在售中自营商品总数
        $onsaleOwnCount = db("goods")->where("show",1)->where("goods_status",1)->count();


        echo "【自由商城商品数据】：<br><br>";
        echo "商品总数：".$totalCount."<br>";
        echo "在售中商品总数：".$onsaleTotalCount."<br><br>";
        echo "viator商品总数：".$viatorCount."<br>";
        echo "在售中viator商品总数：".$onsaleViatorCount."<br><br>";
        echo "自营商品总数：".$ownCount."<br>";
        echo "在售中自营商品总数：".$onsaleOwnCount."<br><br><br>";



        //产品总数
        $productCount = db("product")->count();
        //供应商产品总数
        $where3['supplier_item_code'] = [["NEQ","null"],["NEQ",""],'and'];
        $supplierProductCount = db("product")->where($where3)->count();

        //自有线路产品总数
        $ownProductCount = $productCount - $supplierProductCount;

        echo "【产品数据】：<br><br>";
        echo "产品总数：".$productCount."<br>";
        echo "自有线路产品总数：".$ownProductCount."<br>";
        echo "供应商产品总数：".$supplierProductCount."<br><br><br>";



        //toB
        //上架包车产品总数
        $standardCarCount = db("standard")->where("type",1)->where("show_toB",1)->count();
        //上架viator商品总数
        $standardViatorData = db("standard")->where("type",2)->where("show_toB",1)->field("id")->select();
        $standardViatorCount = 0;
        foreach ($standardViatorData as $k=>$v) {
            $tagsData = db("standardtags")->where("sid",$v['id'])->find();
            if($tagsData){
                $standardViatorCount++;
            }
        }


        echo "【toB上架数据】：<br><br>";
        echo "上架包车产品总数：".$standardCarCount."<br>";
        echo "上架viator商品总数：".$standardViatorCount."<br>";




        exit;
    }

    //aes 加解密测试
    public function aes_encode()
    {
//        $string = 'appid=KBX2B&token=123456789';
//        $encodestring = (new Aes())->encode($string);
//        var_dump($encodestring);
//        $decodestring = (new Aes())->decode($encodestring);
//        var_dump($decodestring);

//        $encodestring = (new Rsa())->encode('1=2&3=4');
//
//        var_dump((new Rsa())->decode($encodestring));

//            $arr = [];
//            $string = http_build_query($arr);
//            parse_str($string,$arr2);
//            var_dump($string,gettype($arr2));
//        "12345678"=>"MzcxMjM0NTY3OA=="
//        $encode = (new Selfmcrypt())->encode("59D-Id7THQ1");
//        echo $encode;
        $decode = (new Selfmcrypt())->decode("eUJaeUt0a0JVa0xS");
        echo $decode;
    }

    //更新所有关联产品的商品信息
    public function updateGoodsInfo()
    {
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去
        $list = db('goods')
            ->field('goods_id,goods_tcode,price_include,price_noinclude,goods_careful,goods_retreating')
            ->where("goods_tcode is not null and goods_tcode != ''")
//            ->where("goods_id = 30672")
            ->select();
        //return json_encode($list);
        log::log("开始刷新商品信息");

        db::startTrans();
        try{
            foreach ($list as $key=>$value){
                db('goods')->where('goods_id',$value['goods_id'])->update([
                   'price_include'=>str_replace("\r\n",'<br>',$value['price_include']),
                   'price_noinclude'=>str_replace("\r\n",'<br>',$value['price_noinclude']),
                   'goods_careful'=>str_replace("\r\n",'<br>',$value['goods_careful']),
                   'goods_retreating'=>str_replace("\r\n",'<br>',$value['goods_retreating']),
                ]);
                log::log("刷新商品id:".$value['goods_id']);
            }
            db::commit();
            log::log("刷新结束");
            echo "success";
        }catch (Exception $e){
            db::rollback();
            log::log("刷新失败".json_encode($e->getMessage()));
            echo json_encode($e->getMessage());
        }

    }

    //测试刷新拼游小程序的userToken
    public function refreshToken()
    {
        $member_id = input('member_id',0);
        if(!empty($member_id)){
            $token = md5(time());
            db('member')->where('member_id',$member_id)->update([
                'grouptour_token'=>$token,
                'grouptour_token_time'=>time()+7*24*3600
            ]);
        }else{
            return json_encode(['code'=>-100,'msg'=>'缺少member_id']);
        }
        return json_encode(['code'=>200,'msg'=>'success','data'=>$token]);
    }

    //将viator的code复制到goods_tcode
    public function copyCodeToGoodsTcode()
    {
        ignore_user_abort();
        set_time_limit(0);
        trace(date('Y-m-d H:i:s').'viator商品更新goods_tcode开始');
        $where['show'] = ['exp',new Expression(' = 2 and code!="" and code is not null and (goods_tcode="" or goods_tcode is null)')];
        $list = db('goods')->field('goods_id,code,goods_tcode')
            ->where($where)
            ->select();
        if(empty($list)){
            trace(date('Y-m-d H:i:s').'暂无数据需要更新');
            trace(date('Y-m-d H:i:s').'viator商品更新goods_tcodes结束');
            return json_encode(['code'=>200,'msg'=>'暂无数据需要更新']);

        }
        db::startTrans();

        try{
            foreach ($list as $key=>$value){
                if(empty($value['goods_tcode']) && !empty($value['code'])){
                    db('goods')->where('goods_id',$value['goods_id'])->update([
                        'goods_tcode'=>$value['code']
                    ]);
                    trace(date('Y-m-d H:i:s').'viator商品ID【'.$value['goods_id'].'】成功');
                }
            }
            db::commit();
            trace(date('Y-m-d H:i:s').'viator商品更新goods_tcodes结束');
            return json_encode(['code'=>200,'msg'=>'更新成功']);
        }catch (Exception $e){
            db::rollback();
            trace(date('Y-m-d H:i:s').'viator商品更新失败原因是'.$e->getMessage());
            return json_encode(['code'=>400,'msg'=>'更新失败，原因是'.$e->getMessage()]);
        }

    }

}
